﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using TencentCloud.Emr.V20190103.Models;
using ZenSystemService.Api.Common.HttpCommunication;
using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Common.Auth
{
    public static class AuthUtilExtensions
    {
        public static void AddAuthUtilServices(this IServiceCollection services,IConfiguration configuration)
        {
            var jwtSettings = configuration.GetSection("JwtSettings");
            var secretKey = jwtSettings["SecretKey"];
            var issuer = jwtSettings["Issuer"];
            var audience = jwtSettings.GetSection("ValidAudience").Get<string[]>();

            ApiOptions apiOptions = configuration.GetSection("ApiOptions").Get<ApiOptions>();
            ICollection<ServiceApiOptions> Services = apiOptions.Services;
            var zenBrightConfig = Services.FirstOrDefault(s => s.ApiName == "ZenBright");

            // ApiUtility.ZenBright_BASE_URL = configuration.GetValue<string>("LegencyApiBaseUrl");
            ApiUtility.ZenBright_BASE_URL = zenBrightConfig.BaseAddress.TrimEnd('/') + '/';
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidAudiences = audience, 
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)),
                    ValidIssuer = issuer
                };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
                        if (!string.IsNullOrEmpty(token))
                        {
                            var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
                            logger.LogInformation("Received JWT token: {Token}", token);
                        }
                        return Task.CompletedTask;
                    },
                    OnAuthenticationFailed = context =>
                    {
                        var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
                        logger.LogError(context.Exception, "Authentication failed: {Message}", context.Exception.Message);
                        return Task.CompletedTask;
                    }
                };
            });

            services.AddScoped<TokenService>();
        }
    }
}

